import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserManageService } from 'app/services/manage/user-manage.service'

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.less']
})
export class UserDetailComponent implements OnInit {

  private userId = null // 用户ID
  private userForm: FormGroup

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private modalService: NzModalService,
    private messageService: NzMessageService,
    private fb: FormBuilder,
    private userManageService: UserManageService
  ) {
    // 获取用户ID
    this.userId = this.route.snapshot.params.id;

    this.userForm = fb.group({
      username: [],
      realname: [],
      phonenumber: [],
      email: []
    })
  }


  /**
   * 初始化
   */
  ngOnInit() {
    if (this.userId) {
      this.userManageService.getUser(this.userId)
        .then((data: any) => {
          this.userForm.setValue({
            username: data.username,
            realname: data.realname,
            email: data.email,
            phonenumber: data.phonenumber,
          })
        })
    }
  }

  /**
   * 显示认证窗口
   * @param contentTpl
   * @param footerTpl
   */
  submitForm(contentTpl, footerTpl) {
    this.userId ? this.updateUser() : this.addUser()
  }

  /**
   *添加用户
   */
  addUser() {
    this.userManageService.addUser({
      username: this.userForm.value.username,
      realname: this.userForm.value.realname,
      phonenumber: this.userForm.value.phonenumber,
      email: this.userForm.value.email
    }).subscribe(
      () => {
        console.log(123)
        this.messageService.create('success', '保存成功')
        this.router.navigate(['user-manage'])
      },
      error => this.messageService.create('error', error))
  }

  /**
   * 更新用户
   */
  updateUser() {
    this.userManageService.updateUser(this.userId,
      {
        username: this.userForm.value.username,
        realname: this.userForm.value.realname,
        email: this.userForm.value.email,
        phonenumber: this.userForm.value.usernphonenumberame,
      }).then(
      () => {
        this.messageService.create('success', '保存成功')
        this.router.navigate(['user-manage'])
      },
      error => this.messageService.create('error', error))
  }
}
